package com.website.shiro;

import com.yufeixuan.captcha.utils.CaptchaUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登陆控制
 *
 * @author zhangshuw
 * @date 2017/6/9
 */
@RestController
public class Login {

    @Resource
    ShiroFilterFactoryBean bean;

    /**
     * 未通过FormAuthenticationFilter
     * 登录页面或登录失败后跳转到此
     *
     * @param mv
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "login")
    public ModelAndView login(ModelAndView mv, HttpServletRequest request, ServletResponse response) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated() || subject.isRemembered()) {
            //已登录则跳转
            WebUtils.redirectToSavedRequest(request, response, bean.getSuccessUrl());
            return null;
        }
        Object e = request.getAttribute(FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
        if (e instanceof Exception) {
            //登录异常
            Exception ex = (Exception) e;
            mv.addObject("error", ex.getMessage());
            mv.setViewName("login");
        }
        return mv;
    }

    @GetMapping(value = "/captcha")
    public void getCaptcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        HttpSession session = request.getSession();
        if (session == null) {
           SecurityUtils.getSubject().getSession();
        }
        CaptchaUtil.out(4, request, response);
    }
}
